package org.jeecg.modules.contract.review.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.entity.BussContractReviewDes;
import org.jeecg.modules.business.entity.BussContractReviewDesFiles;
import org.jeecg.modules.contract.pattern.entity.ErpGoodsPattern;
import org.jeecg.modules.contract.review.entity.BussContractRequirementReview;
import org.jeecg.modules.contract.review.service.IBussContractRequirementReviewService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.contract.review.vo.BussContractRequirementReviewVo;
import org.jeecg.modules.erp.base.entity.ErpCustomer;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.mapper.FlowMyBusinessMapper;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 合同要求评审表
 * @Author: jeecg-boot
 * @Date:   2024-05-30
 * @Version: V1.0
 */
@Api(tags="合同要求评审表")
@RestController
@RequestMapping("/review/bussContractRequirementReview")
@Slf4j
public class BussContractRequirementReviewController extends JeecgController<BussContractRequirementReview, IBussContractRequirementReviewService> {
	@Autowired
	private IBussContractRequirementReviewService bussContractRequirementReviewService;
	@Autowired
	private ISysUserService sysUserService;
	 @Autowired
	 private IFlowDefinitionService flowDefinitionService;

	 @Autowired
	 private FlowMyBusinessMapper flowMyBusinessMapper;
	/**
	 * 分页列表查询
	 *
	 * @param bussContractRequirementReview
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "合同要求评审表-分页列表查询")
	@ApiOperation(value="合同要求评审表-分页列表查询", notes="合同要求评审表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BussContractRequirementReviewVo>> queryPageList(BussContractRequirementReview bussContractRequirementReview,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		//查自己的
//		SysUser sysUser = sysUserService.getUserByName(JwtUtil.getUserNameByToken(req));
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (sysUser!=null) {
//			bussContractRequirementReview.setUserId(sysUser.getId());
		}
		QueryWrapper<BussContractRequirementReview> queryWrapper = QueryGenerator.initQueryWrapper(bussContractRequirementReview, req.getParameterMap());
		Page<BussContractRequirementReview> page = new Page<BussContractRequirementReview>(pageNo, pageSize);
		IPage<BussContractRequirementReviewVo> pageList = bussContractRequirementReviewService.myPage(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param bussContractRequirementReviewVo
	 * @return
	 */
	@AutoLog(value = "合同要求评审表-添加")
	@ApiOperation(value="合同要求评审表-添加", notes="合同要求评审表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_contract_requirement_review:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BussContractRequirementReviewVo bussContractRequirementReviewVo) {
		BussContractRequirementReview bussContractRequirementReview = new BussContractRequirementReview();
		BeanUtils.copyProperties(bussContractRequirementReviewVo, bussContractRequirementReview);
		//获取登录用户信息

		String id = bussContractRequirementReviewService.saveMain(bussContractRequirementReview,bussContractRequirementReviewVo.getErpGoodsPackageList());
		return Result.OK(id);
	}
	
	/**
	 *  编辑
	 *
	 * @param bussContractRequirementReviewVo
	 * @return
	 */
	@AutoLog(value = "合同要求评审表-编辑")
	@ApiOperation(value="合同要求评审表-编辑", notes="合同要求评审表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_contract_requirement_review:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BussContractRequirementReviewVo bussContractRequirementReviewVo) {
		BussContractRequirementReview bussContractRequirementReview = new BussContractRequirementReview();
		BeanUtils.copyProperties(bussContractRequirementReviewVo, bussContractRequirementReview);
		BussContractRequirementReview requirementReview = bussContractRequirementReviewService.getById(bussContractRequirementReview.getId());
		if(requirementReview==null) {
			return Result.error("未找到对应数据");
		}
		bussContractRequirementReviewService.updateMain(bussContractRequirementReview,bussContractRequirementReviewVo.getErpGoodsPackageList());
		return Result.OK(bussContractRequirementReview.getId());
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同要求评审表-通过id删除")
	@ApiOperation(value="合同要求评审表-通过id删除", notes="合同要求评审表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_contract_requirement_review:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		bussContractRequirementReviewService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同要求评审表-批量删除")
	@ApiOperation(value="合同要求评审表-批量删除", notes="合同要求评审表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:buss_contract_requirement_review:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bussContractRequirementReviewService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合同要求评审表-通过id查询")
	@ApiOperation(value="合同要求评审表-通过id查询", notes="合同要求评审表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BussContractRequirementReview> queryById(@RequestParam(name="id",required=true) String id) {
		BussContractRequirementReview bussContractRequirementReview = bussContractRequirementReviewService.getById(id);
		if(bussContractRequirementReview==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bussContractRequirementReview);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param bussContractRequirementReview
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_contract_requirement_review:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussContractRequirementReview bussContractRequirementReview) {
        return super.exportXls(request, bussContractRequirementReview, BussContractRequirementReview.class, "合同要求评审表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("buss_contract_requirement_review:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BussContractRequirementReview.class);
    }
	 @ApiOperation(value="根据id查询打印预览需要的数据", notes="根据id查询打印预览需要的数据")
	 @GetMapping(value = "/getPrintViewData/{id}")
	 public Result<List> getPrintViewData(@PathVariable("id") String id) {
		 BussContractRequirementReview review = bussContractRequirementReviewService.getById(id);
		 review.setPrintFlag(1);
		 bussContractRequirementReviewService.updateById(review);
		 String desId = review.getDesId();
		 ArrayList<Map<String, Object>> maps = new ArrayList<>();
		 HashMap<String, Object> map = new HashMap<>();

		 map.put("title","合同评审说明");
		 map.put("templateId","970575111953915904");
		 ArrayList<Map<String, Object>> inData = new ArrayList<>();
		 HashMap<String, Object> inMap = new HashMap<>();
		 inMap.put("id",desId);
		 inData.add(inMap);
		 map.put("data",inData);

		 maps.add(map);
		 maps.add(map);
		 return Result.ok(maps);
	 }
	 /**
	  * 反审核
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "合同评审说明-反审核")
	 @ApiOperation(value = "合同评审说明-反审核", notes = "合同评审说明-反审核")
	 @GetMapping(value = "/reverseCheck")
	 public Result<BussContractReviewDes> reverseCheck(@RequestParam(name = "id", required = true) String id) {
		 BussContractRequirementReview review = bussContractRequirementReviewService.getById(id);
		 if (review == null) {
			 return Result.error("未找到对应数据");
		 }
		 BussContractRequirementReview copyReview = new BussContractRequirementReview();
		 BeanUtils.copyProperties(review, copyReview);
		 copyReview.setId(null);
		 copyReview.setCreateTime(null);
		 copyReview.setUpdateTime(null);
		 copyReview.setUpdateBy(null);
		 copyReview.setCreateBy(null);
		 bussContractRequirementReviewService.save(copyReview);
		 //孙春鹏 todo：
		 //主表信息已存在  查询出原主表关联的子表对应所有列表信息   一一保存 关联到这个主表id上
		 bussContractRequirementReviewService.copyInfo(id,copyReview.getId());
		 String dataId = copyReview.getId();
		 BeanMap variables = new BeanMap(copyReview);
		 FlowMyBusiness flowMyBusiness = flowMyBusinessMapper.selectOne(new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getDataId, id).last(" limit 1"));
		 if (Objects.isNull(flowMyBusiness)) {
			 return Result.error("该表单尚未发起审批,不可以发起反审核操作");
		 }
		 String actStatus = flowMyBusiness.getActStatus();
		 if (!"审批通过".equals(actStatus)) {
			 return Result.error("只有审批通过的表单可以发起反审核操作");
		 }
		 // 转换为 Map<String, Object>
		 Map<String, Object> map = new HashMap<>();
		 for (Object key : variables.keySet()) {
			 map.put((String) key, variables.get(key));
		 }
		 map.put("dataId", dataId);
		 return flowDefinitionService.startProcessInstanceByDataId(dataId, "contractRequirementReviewService", map);
	 }


}
